//微信适配
if(Config.channelID == 1){
   Laya.MiniAdpter.init(true);
}
// oppo
if(Config.channelID == 101 && typeof qg != "undefined"){
    laya.quickgame.mini.MiniAdpter.init();
    qg.onShow(function() {
        Audio.resumeAll();
        if(Config._playState) {
            if(Config._playEnd) {
                Config._playEnd();
                Config._playEnd = null;
            }else {
                Config._playRelive.isUpdate = true;
                Laya.timer.frameLoop(1, Config._playRelive, Config._playRelive.timeLoop);
            }
            Config._playState = null;
        }
    })
}
// 华为
if(Config.channelID == 0){
   Laya.MiniAdpter.init(true);
}
//iphonex适配(大屏适配)
var w1 = Laya.Browser.clientWidth;
var h1 = Laya.Browser.clientHeight;
var baseRate = Config.GameHeight / Config.GameWidth;
var curRate = h1 / w1;
var offH = 0;
if(curRate > baseRate){
   offH = curRate * Config.GameWidth - Config.GameHeight;
   Config.GameHeight *= curRate/baseRate
}
//初始化引擎
Laya3D.init(Config.GameWidth, Config.GameHeight,true);

//适配模式
Laya.stage.scaleMode = "showall";
Laya.stage.screenMode = "vertical";
//设置水平对齐
Laya.stage.alignH = "center";
//设置垂直对齐
Laya.stage.alignV = "middle";
BaseData.init();
//开启统计信息
//Laya.Stat.show();
//测试开启新手引导
//BaseData.saveGameData("guide",0);
//新手引导控制
//Config.guideStep = BaseData.getGameData("guide");

/**
 * oppo或者vivo插屏广告出项的概率api
 */
if(Config.channelID == 101 || Config.channelID == 102) {
    RequestTep("POST", "https://xyx.lfungame.com/common/get_rand_value", {}, function(data) {
        // 访问成功
        Tool.log("-------init vivo ad data.rand_value -------", JSON.stringify(data.data));
        Config.InsertP =50;
    }, function(data) {
        // 访问失败
    })
}

//资源加载
if(Config.channelID == 1){
   Laya.URL.basePath = Config.downUrl;
   //开启转发
   wx.showShareMenu({withShareTicket: true});

   //监听背景音乐后台回来
   wx.onShow(function () {
       Audio.resumeAll();
   });

   //微信更新
   if (wx.getUpdateManager) {
        var updateManager = wx.getUpdateManager();
        updateManager.onCheckForUpdate(function (res) {
            // 请求完新版本信息的回调
            if(res.hasUpdate){
               console.log("用户新版本更新了...");
            }
        });
        
        updateManager.onUpdateReady(function () {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate();
        });
   }

   //获取微信的数据
   if(wx.getStorage){
        wx.getStorage({
            key : "score",
            success:function(res){
                console.log(res);
                gameScore = res.data;
            },
        });
   }
   
   /*  //用户信息授权
   wx.getSetting({
    success: function (res) {
        var authSetting = res.authSetting
        if (authSetting['scope.userInfo'] === true) {
            // 用户已授权，可以直接调用相关 API

        } else if (authSetting['scope.userInfo'] === false){
            // 用户已拒绝授权，再调用相关 API 或者 wx.authorize 会失败，需要引导用户到设置页面打开授权开关
            wx.openSetting({
                success: res =>{

                },
            });
        } else {
           // 未询问过用户授权，调用相关 API 或者 wx.authorize 会弹窗询问用户
            wx.authorize({
                scope: 'scope.userInfo'
            });
        }
    }
  });*/
}

//并发加载
Laya.loader.maxLoader = 5;

/**
 * 判断是否在华为环境下
 */
if(Config.channelID == 103) {
    var huaweiId = "100728231";

    hbs.gameLogin({
        forceLogin: 1, //强制登陆，未登陆时会弹出登陆对话框
        appid: huaweiId,
        success: function (res) {
            loginSuccess = 0; //记录登录成功标记
            showFloatingWin(); //显示浮标
            // console.log("---------- huawei game login: success");
        },
        fail(data, code) {
            loginSuccess = -1;
            // console.log("---------- huawei on gameLogin fail: " + data + "," + code);
        },
        complete() {
            // console.log("---------- huawei on gameLogin: complete");
        }
    })

   /**
         * 显示游戏浮标窗口
    */
    function showFloatingWin() {
        hbs.showFloatWindow({
            appid: huaweiId, //appid需要与华为开发者联盟后台配置一致
            success: function () {
                // console.log("---------- huawei show float window success.");
            },
            fail: function (data, code) {
                // console.log("---------- huawei show float window fail:" + data + ", code:" + code);
            }
        });
    }

    /** 
        *  隐藏浮标窗口
    */
    function hideFloatingWin() {
        hbs.hideFloatWindow({
            appid: huaweiId,
            success: function () { 
                // console.log("---------- huawei hide float window success");
            },
            fail: function (data, code) { 
                // console.log("---------- huawei hide float window fail:" + data + ", code:" + code);
            }
        });
    }

    var cbShow = function () {
        // console.log("---------- huawei --------on show----------");
        // 如果登录成功显示浮标
        if (loginSuccess === 0) {
            this.showFloatingWin();
        }
    }.bind(this);

    var cbHide = function () {
        // console.log("---------- huawei --------on hide----------");
        this.hideFloatingWin();
    }.bind(this);

    // 注册onShow/onHide回调，用于隐藏和显示浮标
    hbs.onShow(cbShow);
    hbs.onHide(cbHide);
}

var _isFromUrl = false;
// if(window.hbs && _isFromUrl) {
//     var that = this;
//     hbs.downloadFile({
//         url: window.Config.fileDownUrl,
//         filePath: hbs.env.USER_DATA_PATH + "/ytdd.zip",
//         success: function(res) {
//             var filePath = res.filePath;
//             var fsmgr = hbs.getFileSystemManager();
//             fsmgr.unzip({
//                 zipFilePath: filePath,
//                 targetPath: hbs.env.USER_DATA_PATH + window.Config.fileDir,
//                 success: function (res) {
//                     // console.log("---------- huawei fileSystemManager --------" + JSON.stringify(res));
//                     // console.log("---------- huawei fileSystemManager --------", hbs.env.USER_DATA_PATH +window.Config.fileDir + "res/atlas/loading.atlas");
//                     // var content = fsmgr.readFileSync(hbs.env.USER_DATA_PATH + window.Config.fileDir + "LayaScene_game/game.ls", "utf8");
//                     // console.log("---------- huawei fileSystemManager 111111111 --------", content);

//                     Laya.loader.load(loadFile, Laya.Handler.create(that,beginLoading));
//                 },  
//                 fail: function (err) {
//                     console.log("---------- huawei fileSystemManager fail --------", JSON.stringify(err));
//                 }
//             })
//         },
//         fail: function(err) {
//             console.log("---------- huawei download fail --------------", JSON.stringify(err));
//         },
//         complete: function() {
//             // console.log("---------- huawei download complete --------------");
//         }
//     }) 
// }else {
//     Laya.loader.load(loadFile,Laya.Handler.create(this,beginLoading));
// }
Laya.loader.load(loadFile,Laya.Handler.create(this,beginLoading));



var GlobalScene = null;
var GlobalCamera = null;
var GlobalLight = null;
var GlobalColumn = null;
var GlobalPlayerBall = null;
var GlobalPlayerBallInvincible = null;
var GlobalEatCapsuleEff = null;
var GlobalThorn = null;
var GlobalBaffle = null;
var GlobalSphere = null;
var GlobalSphereRed = null;
var GlobalCapsule = null;
var GlobalWood = null;
var GlobalCollisionEff = null;
var GlobalCollisionEffRed = null;
var GlobalCapsuleEffDown = null;
var GlobalCapsuleEffBg = null;
var GlobalCapsuleEffBall = null;
var GlobalCarpetArr = [];
var GlobalGroundArr = [];
var GlobalBgEff = [];

var GlobalFloorBox = null;
var __RankDlg = null;
var __RankDlgShow = false;

function beginLoading(){
    LoadingSceneObj = new LoadingScene();
    //Laya.stage.addChild(LoadingSceneObj);
    LoadingSceneObj.init("LoadingScene");
    LoadingSceneObj.active();
    LoadingSceneObj.setLoadedCB(function () {
        initGame();
    })
    loadGameData()
    if(Config.channelID==101){
        let count=AssetsFileArr.length;
        for (let index = 0; index < count; index++) {
            let tempUrl= Config.oppofileDownUrl+ AssetsFileArr[index].url;
            AssetsFileArr[index]=tempUrl;
        }
        console.log(AssetsFileArr);
    }
     Laya.loader.load(AssetsFileArr,Laya.Handler.create(this,loadControl));
    load3D()
    if(Config.channelID == 1){
        var musicStep = 0;
        var musicNum = loadMusic.length;
        for (var i = 0; i < loadMusic.length; i++) {
            var musicUrl = loadMusic[i].url;
            Laya.timer.frameOnce(i,this,function () {
                var miniSound = new Laya.MiniSound();
                miniSound.load(musicUrl);
                miniSound.on("complete",this,function(){
                    musicStep += 1;
                    if(musicStep === musicNum){
                        loadControl();
                    }
                });
            });
        }
    }else if(Config.channelID == 102){        
        loadControl();
    }else{
        if(Config.channelID==101){
        let count=loadMusic.length;
        for (let index = 0; index < count; index++) {
            let tempUrl= Config.oppofileDownUrl+ loadMusic[index].url;
            loadMusic[index]=tempUrl;
        }
  
    }
        Laya.loader.load(loadMusic,Laya.Handler.create(this,loadControl));
        // Laya.loader.load(parseFileArr);
    }
}

//加载完回调
function loadControl(){
    // 进度条增加 每次加30%
    LoadingSceneObj.increaseLodingValue(30);
};

function load3D(){
    // 添加3D场景
    if(Config.channelID == 1){
        GlobalScene =  Laya.Scene.load("LayaScene_wx/wx.ls");
    }if(Config.channelID == 103){
        if (_isFromUrl){
            GlobalScene =  Laya.Scene.load(hbs.env.USER_DATA_PATH + window.Config.fileDir + "LayaScene_game/game.ls");
        }else{
            GlobalScene =  Laya.Scene.load("res/LayaScene_game/game.ls");
        }
    }else if(Config.channelID == 101){
          GlobalScene =  Laya.Scene.load(Config.oppofileDownUrl+"LayaScene_game/game.ls");
    }
    else{
        GlobalScene =  Laya.Scene.load("LayaScene_game/game.ls");
    }
    GlobalScene.zOrder = -1;

    GlobalScene.once(Laya.Event.HIERARCHY_LOADED, this, function (_scene) {
        setCloneFather(_scene);
        // GlobalCamera.addComponent(CameraMoveScript);
        //圆柱体
        GlobalFloorBox = _scene.addChild(new Laya.MeshSprite3D(new Laya.CylinderMesh(1, 1)));
        GlobalFloorBox.transform.position = new Laya.Vector3(0,0,0);
        GlobalFloorBox.transform.rotate(new Laya.Vector3(0,90,0), false, false);
        GlobalCamera.transform.position = new Laya.Vector3(0,Config.GlobalCameraPositionYY,Config.GlobalCameraPositionZZ);
        // 将所有节点 删除，并且activi设置为false,等到游戏时 再显示，性能优化
        for (var _index = 2; _index < 100; _index++) {
            var element = _scene.getChildAt(_index);
            if(element){
                // _scene.removeChildren(element);
                element.active = false;
            }
        }
        //逻辑控制
        loadControl();
    });
}

function setCloneFather(_scene){
        // _scene =  Laya.Scene.load(hbs.env.USER_DATA_PATH + window.Config.fileDir + "LayaScene_game/game.ls");

        GlobalCamera = _scene.getChildByName("Main Camera");
        GlobalLight = _scene.getChildByName("Directional Light");   
        GlobalColumn = _scene.getChildByName("Column");
        GlobalCapsule = _scene.getChildByName("Capsule");
        GlobalWood = _scene.getChildByName("Wood");
        GlobalThorn = _scene.getChildByName("Thorn");
        GlobalBaffle = _scene.getChildByName("Baffle");
        if(Config.channelID == 1){
            GlobalPlayerBall = _scene.getChildByName("PlayerBall_wx");
            GlobalPlayerBallInvincible = _scene.getChildByName("PlayerBall_wx");
            GlobalCollisionEff = _scene.getChildByName("ToGroundEff");
            GlobalCollisionEffRed = _scene.getChildByName("ToGroundEff");
            GlobalEatCapsuleEff = _scene.getChildByName("CapsuleEat_wx");
            GlobalCapsuleEffDown = _scene.getChildByName("CapsuleEffDown");
            GlobalCapsuleEffBg = _scene.getChildByName("CapsuleEffBg");
            GlobalCapsuleEffBall = _scene.getChildByName("CapsuleEffBall");
            GlobalBgEff.push(_scene.getChildByName("game_bg_1"));
        }else{
            GlobalEatCapsuleEff = _scene.getChildByName("CapsuleEat");
            GlobalPlayerBall = _scene.getChildByName("PlayerBall");
            GlobalSphere = _scene.getChildByName("Sphere");
            GlobalCollisionEff = _scene.getChildByName("Splash");
            GlobalPlayerBallInvincible = _scene.getChildByName("PlayerBallInvincible");
            GlobalSphereRed = _scene.getChildByName("SphereRed");
            GlobalCollisionEffRed = _scene.getChildByName("SplashRed");
            GlobalBgEff.push(_scene.getChildByName("game_bg_1"));
            GlobalBgEff.push(_scene.getChildByName("game_bg_2"));
            GlobalBgEff.push(_scene.getChildByName("game_bg_3"));
        }
        GlobalCarpetArr.push(_scene.getChildByName("Carpet_30"));
        GlobalCarpetArr.push(_scene.getChildByName("Carpet_60"));
        GlobalCarpetArr.push(_scene.getChildByName("Carpet_90"));

        GlobalGroundArr.push(_scene.getChildByName("ground_1"));
        GlobalGroundArr.push(_scene.getChildByName("ground_2"));
        GlobalGroundArr.push(_scene.getChildByName("ground_3"));
        GlobalGroundArr.push(_scene.getChildByName("ground_4"));
        GlobalGroundArr.push(_scene.getChildByName("ground_5"));
        GlobalGroundArr.push(_scene.getChildByName("ground_6"));
        GlobalGroundArr.push(_scene.getChildByName("ground_7"));
        GlobalGroundArr.push(_scene.getChildByName("ground_8"));
        GlobalGroundArr.push(_scene.getChildByName("ground_9"));
        GlobalGroundArr.push(_scene.getChildByName("ground_10"));
        GlobalGroundArr.push(_scene.getChildByName("ground_11"));
        GlobalGroundArr.push(_scene.getChildByName("ground_12"));
        // GlobalLight.transform.translate(new Laya.Vector3(0,5,0));
        //设置灯光方向
        // GlobalLight.direction = new Laya.Vector3(0.3, -1, 0);
        //设置灯光漫反射颜色
        // GlobalLight.diffuseColor = new Laya.Vector3(1, 0, 0);
        //设置灯光高光色
        // GlobalLight.specularColor = new Laya.Vector3(0, 0.5, 0.5);
        //添加灯光投影
        // GlobalLight.shadow=true;
        // //产生投影的范围（如过小将不会产生投影）
        // GlobalLight.shadowDistance=100;
        // //生成阴影贴图数量
        // GlobalLight.shadowPSSMCount = 1;
        // //模糊等级,越大越高,效果更好，更耗性能
        // GlobalLight.shadowPCFType=3;
        // //投影质量
        // GlobalLight.shadowResolution=2048;

        // //产生阴影
        // GlobalPlayerBall.meshRender.castShadow=true;
        // GlobalPlayerBallInvincible.meshRender.castShadow=true;
        
        for (var i = 0; i < GlobalGroundArr.length; i++) {
            var _ground = GlobalGroundArr[i];
            _ground.meshRender.receiveShadow=true;
        }
        for (var i = 0; i < GlobalCarpetArr.length; i++) {
            var _carpet = GlobalCarpetArr[i];
            _carpet.meshRender.receiveShadow=true;
        }
        GlobalColumn.meshRender.receiveShadow=true;
}
function initGame() {
    Laya.stage.addChild(GlobalScene);
    //渠道对接
    if(Config.channelID == 100){
        window.OPPO.login({
            packageName:"com.lywx.ytdd.h5.nearme.gamecenter",//开发者在oppo开放平台填写的包名
            callback:function(res){
                console.log(res)
            }
        });
    }
    // Audio.playBg()
    loadScenes();
    loadActions();
    Laya.stage.addChild(GlobalScene);
    SceneManager.toggleAction("home");

    if(Config.channelID == 2 && typeof BK != "undefined"){
        function gameCloseListener(){
            ResultSceneObj._ResultSceneView.uploadQQRankData();
            if(HomeSceneObj.gameRoom && HomeSceneObj.gameRoom.leaveRoom){
                HomeSceneObj.gameRoom.leaveRoom(function(){})
            }
            
        }
        BK.onGameClose(gameCloseListener);
    }
    if(Config.channelID == 101 && typeof qg != "undefined"){
        qg.initAdService({  
            appId : "30000560",  
            isDebug : false,  
            success : function(res) {    
                Config.isLoadSuccess = true;
                Tool.log("-------init oppo ad--------success");  
            },  
            fail : function(res) {    
                Tool.log("-------init oppo ad--------fail:" + res.code + res.msg);  
            },
            complete: function(res) {    
                Tool.log("-------init oppo ad--------complete");  
            } 
        })
    }
}
function loadScenes(){
    SceneManager.addScene("HomeScene", (HomeSceneObj = new HomeScene()));
    SceneManager.addScene("GameScene", (GameSceneObj = new GameScene()));
    SceneManager.addScene("ResultScene",(ResultSceneObj = new ResultScene()));
}

function loadActions(){
    SceneManager.addAction("home", null, "HomeScene");
    SceneManager.addAction("start_game", "HomeScene", "GameScene");
    SceneManager.addAction("game_end", "GameScene", "ResultScene");
    SceneManager.addAction("game_again", "ResultScene", "GameScene");
    SceneManager.addAction("return_home", "ResultScene", "HomeScene");
}

//所有变化的内容重置
function globeReset(){
    GameSceneObj.resetGame();
}

function loadGameData() {
    if(Config.channelID == 1){
        wx.request({
            url: "https://xyx.lfungame.com/lwgame/get_recommend_game?game=qqytdd",
            data: {
                game: "qqytdd"
            },
            success: function(res) {
                if(res.data.code == 0){
                    BaseData.saveUserData("recommend_game_ytdd",res.data.data);
                }else{
                    var testDlg = new ErrTips("网络错误",2000);
                }
            },
            fail: function () {
                var testDlg = new ErrTips("网络错误",2000)
            },
            complete: function () {
                LoadingSceneObj.increaseLodingValue(10);
                var gameDataStr = BaseData.getUserData("recommend_game_ytdd");
                var gameData = JSON.parse(gameDataStr);
                BaseData.saveGameData(gameData);
            },
        })
    }else{
        LoadingSceneObj.increaseLodingValue(10);
    }
}


